package com.spring.springboot.sys.jwt;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spring.springboot.entity.User;
import com.spring.springboot.service.UserService;
import com.spring.springboot.sys.core.constant.BusinessConstant;
import com.spring.springboot.sys.core.model.UserInfo;
import com.spring.springboot.sys.core.model.WebUserDetails;
import com.spring.springboot.sys.util.UserInfoUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.annotation.Resource;

/**
 * @author 宋义州
 * @date 2022-08-10  01:06
 * @description 自定义实现UserDetailsService，做用户信息操作
 */
@Slf4j
@Configuration
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserService userService;

    /**
     * 根据自己的业务做操作
     *
     * @param username the username identifying the user whose data is required.
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = UserInfoUtils.getUserInfo();
        WebUserDetails webUserDetails = null;
        long startTime = System.currentTimeMillis();
        User user = userService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getDelFlag, BusinessConstant.DeleteStatus.NO_DELETE)
                .eq(User::getAccount, username));
        log.info("获取用户信息耗时:{}", (System.currentTimeMillis() - startTime));
        if (ObjectUtils.isNotEmpty(user)) {
            BeanUtils.copyProperties(user, userInfo);
            webUserDetails = new WebUserDetails(userInfo);
            UserInfoUtils.setUserInfo(userInfo);
        }

        return webUserDetails;
    }
}
